﻿/*
 * Copyright(C) 2012,ajayumi 保留所有权利。( All rights reserved. )
 * 
 * 文件名称：HtmlHelper.cs
 * 摘    要：
 * 当前版本：1.0
 * 作    者：黄乙冬 (ajayumi)
 * 创建日期：2012年5月24日
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace ajayumi.Platform.Web
{
    /// <summary>
    /// HtmlHelper.cs 网页辅助类
    /// Author   : 黄乙冬
    /// Date     : 2011-11-30
    /// </summary>
    public class HtmlHelper
    {
        /// <summary>
        /// 当前系统时间字符串
        /// </summary>
        /// <returns>20090301131022333</returns>
        public static string DateFileName()
        {
            return string.Concat(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);
        }

        /// <summary>
        /// 获取日期字符串
        /// </summary>
        /// <returns></returns>
        public static string GetDateTimeStr()
        {
            return DateTime.Now.ToString("yyyyMMddHHmmssfff");
        }
        /// <summary>
        /// 获取日期字符串
        /// </summary>
        /// <param name="format">格式字符串</param>
        /// <returns></returns>
        public static string GetDateTimeStr(string format)
        {
            return DateTime.Now.ToString(format);
        }


        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str">待截取的字符串</param>
        /// <param name="len">截取的长度</param>
        /// <returns></returns>
        public static string CutStr(string str, int len)
        {
            if (str.Length <= len)
                return str;
            else
                return str.Substring(0, len) + "...";
        }

        /// <summary>
        /// 计算总页数
        /// </summary>
        /// <param name="total">总记录数</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns></returns>
        public static int CalcTotalPageNumber(long total, int pageSize)
        {
            int totalPage = 0;
            if (total % pageSize == 0)
            { totalPage = Convert.ToInt32(total / pageSize); }
            else
            { totalPage = Convert.ToInt32(total / pageSize) + 1; }

            return totalPage;
        }
        /// <summary>
        /// 计算总页数
        /// </summary>
        /// <param name="total">总页数</param>
        /// <param name="partSize">每部分显示多少页</param>
        /// <returns></returns>
        public static int CalcTotalPartNumber(int total, int partSize)
        {
            int totalPart = 0;
            if (total % partSize == 0)
            { totalPart = Convert.ToInt32(total / partSize); }
            else
            { totalPart = Convert.ToInt32(total / partSize) + 1; }

            return totalPart;
        }

        /// <summary>
        /// 过滤危险字符，获取安全字符串
        /// </summary>
        /// <param name="str">待过滤的字符串</param>
        /// <returns></returns>
        public static string SafeString(string str)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;

            str = str.Replace("'", string.Empty);
            str = str.Replace(";--", string.Empty);
            str = Regex.Replace(str, "or ", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"or\(", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, "and ", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"and\(", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, "set ", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"exec[\s]*", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"execute[\s]*", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"sp_executesql[\s]*", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"declare[\s]*", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"select[\s]*", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"delete[\s]*", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"drop[\s]*", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            str = Regex.Replace(str, @"alter[\s]*", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return str;
        }

        /// <summary>
        /// 过滤危险字符，获得安全的数字，默认为0
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int SafeInt(string str)
        {
            int reslut = 0;
            int.TryParse(str, out reslut);

            return reslut;
        }

        /// <summary>
        /// 过滤危险字符，获得安全的数字，默认为0
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static long SafeLong(string str)
        {
            long reslut = 0L;
            long.TryParse(str, out reslut);

            return reslut;
        }

        /// <summary>
        /// 清除不安全的Html
        /// </summary>
        /// <param name="htmlStr"></param>
        /// <returns></returns>
        public static string RemoveUnsafeHtml(string htmlStr)
        {
            if (string.IsNullOrEmpty(htmlStr))
            { return string.Empty; }

            htmlStr = Regex.Replace(htmlStr, @"<script[\s\S]+</script *>", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            htmlStr = Regex.Replace(htmlStr, @"<iframe[\s\S]+</iframe *>", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            htmlStr = Regex.Replace(htmlStr, @"<frameset[\s\S]+</frameset *>", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return htmlStr;
        }

        /// <summary>
        /// 对HTML标记进行编码 
        /// </summary>
        /// <param name="htmlStr"></param>
        /// <returns></returns>
        public static string EncodeHtml(string htmlStr)
        {
            string tempStr = RemoveUnsafeHtml(htmlStr);
            tempStr = HttpContext.Current.Server.HtmlEncode(tempStr).Trim();
            tempStr = tempStr.Replace(">", "&gt;");
            tempStr = tempStr.Replace("<", "&lt;");
            tempStr = tempStr.Replace(" ", "&nbsp;");
            tempStr = tempStr.Replace("\'", "&#39;");
            tempStr = tempStr.Replace("\r\n", "<br />");
            return tempStr;
        }

        /// <summary>
        /// 对HTML标记进行解码
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string DecodeHtml(string htmlStr)
        {
            htmlStr = HttpContext.Current.Server.HtmlDecode(htmlStr).Trim();
            htmlStr = htmlStr.Replace("&gt;", ">");
            htmlStr = htmlStr.Replace("&lt;", "<");
            htmlStr = htmlStr.Replace("&nbsp;", " ");
            htmlStr = htmlStr.Replace("&#39;", "\'");
            htmlStr = htmlStr.Replace("<br />", "\r\n");
            return htmlStr;
        }

        ///   <summary> 
        ///   移除HTML标签 
        ///   </summary> 
        ///   <param   name="HTMLStr">HTMLStr</param> 
        public static string RemoveHtmlTags(string htmlStr)
        {
            return Regex.Replace(htmlStr, "<[^>]*>", string.Empty);
        }

        /// <summary>
        /// 取出文本中的图片地址 
        /// </summary>
        /// <param name="HTMLStr"></param>
        /// <returns></returns>
        public static string GetImageUrl(string HTMLStr)
        {
            string str = string.Empty;
            string pattern = @"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>";
            Regex r = new Regex(pattern,
                RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
            Match m = r.Match(HTMLStr);
            if (m.Success) str = m.Result("${url}");
            return str;
        }

        /// <summary>
        /// 将文件大小格式化
        /// </summary>
        /// <param name="fileSize"></param>
        /// <returns></returns>
        public static string FormatFileSize(long fileSize)
        {
            string result = string.Empty;

            if (fileSize <= 0)
            { result = "0 MB"; }
            else
            { result = string.Format("{0:####0.00} MB", ((double)fileSize) / (1024 * 1024)); }

            //if (fileSize <= 0)
            //{ return "0 MB"; }
            //else if (fileSize >= (1024 * 1024 * 1024))
            //{ result = string.Format("{0:########0.00} GB", ((double)fileSize) / (1024 * 1024 * 1024)); }
            //else if (fileSize >= (1024 * 1024))
            //{ result = string.Format("{0:####0.00} MB", ((double)fileSize) / (1024 * 1024)); }
            //else if (fileSize >= 1024)
            //{ result = string.Format("{0:####0.00} KB", ((double)fileSize) / 1024); }
            //else
            //{ result = string.Format("{0} bytes", fileSize); }

            return result;
        }

        /// <summary>
        /// 判断对象是否为Int32类型的数字
        /// </summary>
        /// <param name="Expression"></param>
        /// <returns></returns>
        public static bool IsNumeric(object Expression)
        {
            if (Expression != null)
            {
                string str = Expression.ToString();
                if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*$"))
                {
                    if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1'))
                    {
                        return true;
                    }
                }
            }
            return false;

        }


        public static bool IsDouble(object Expression)
        {
            if (Expression != null)
            {
                return Regex.IsMatch(Expression.ToString(), @"^([0-9])[0-9]*(\.\w*)?$");
            }
            return false;
        }

        /// <summary>
        /// string型转换为bool型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的bool类型结果</returns>
        public static bool StrToBool(object Expression, bool defValue)
        {
            if (Expression != null)
            {
                if (string.Compare(Expression.ToString(), "true", true) == 0)
                {
                    return true;
                }
                else if (string.Compare(Expression.ToString(), "false", true) == 0)
                {
                    return false;
                }
            }
            return defValue;
        }

        /// <summary>
        /// 将对象转换为Int32类型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static int StrToInt(object Expression, int defValue)
        {

            if (Expression != null)
            {
                string str = Expression.ToString();
                if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*$"))
                {
                    if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1'))
                    {
                        return Convert.ToInt32(str);
                    }
                }
            }
            return defValue;
        }

        /// <summary>
        /// string型转换为float型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static float StrToFloat(object strValue, float defValue)
        {
            if ((strValue == null) || (strValue.ToString().Length > 10))
            {
                return defValue;
            }

            float intValue = defValue;
            if (strValue != null)
            {
                bool IsFloat = Regex.IsMatch(strValue.ToString(), @"^([-]|[0-9])[0-9]*(\.\w*)?$");
                if (IsFloat)
                {
                    intValue = Convert.ToSingle(strValue);
                }
            }
            return intValue;
        }
    }
}
